/**
 * 消息管理
 * @authors 杨兴洲（of2502）
 * @date    2017/4/27 21:31
 * @version 1.0
 */

import {Router} from "express";
import Message from "../../service/message-service";
import MessageService from "../../service/message-service";
import UserService from "../../service/user-service";
import WxCustomService from "../../service/weixin-custom-service";
import logger from "../../util/logger";
import AdvancedNewsService from "../../service/advancedNews-service";

const router = Router();

/**
 * 获取消息列表
 */
router.get('/list', (req, res, next) => {
    (async () => {
        try {
            const {page = 1, pageSize = 10, cate = "all", msgType = "text"} = req.query;
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            let result = await Message.getList({appID, page, pageSize, cate, msgType});
            logger.debug(result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});


router.get('/detail', (req, res, next) => {
    (async () => {
        try {
            const {msgID} = req.query;
            if (!msgID) {
                let error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "MsgID不能为空";
                return next(error);
            }

            let result = await Message.getDetail(msgID);
            logger.debug(result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

router.post('/send', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            let {msgID, msgType, toUser, ...rest} = req.body;

            if (!msgID && toUser) {
                let error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "MsgID不能为空";
                return next(error);
            }

            if (msgID) { // 针对性发消息| 获取openID
                let MsgInfo: any = await MessageService.getDetail(msgID);
                if (!MsgInfo) {
                    let error = new Error();
                    error["errcode"] = 10003;
                    error["errmsg"] = "MsgID不存在";
                    return next(error);
                }
                toUser = MsgInfo.fromUser;
            }

            if (msgType === "text") {
                if (!rest.content) {
                    let error = new Error();
                    error["errcode"] = 10003;
                    error["errmsg"] = "文字消息不能为空";
                    return next(error);
                }
                const tp = rest.content.split("__")[0];
                if (["page", "custom", "goods"].includes(tp)) { // 兼容链接
                    rest = {content: rest.content.slice(tp.length + 2, rest.content.length)}
                }
            }

            if (msgType === "news") {
                if (!rest.id) {
                    let error = new Error();
                    error["errcode"] = 10003;
                    error["errmsg"] = "高级图文id参数错误";
                    return next(error);
                }

                let {articles} = await  AdvancedNewsService.getDetail(rest.id);
                if (!articles) {
                    return res.status(200).json({
                        errcode: 10903,
                        errmsg: "id不存在,可能已经被删除"
                    });
                }
                articles = articles.map(item => {
                    const {title, content_source_url, thumb_url, digest} = item;
                    return ({
                        title,
                        description: digest,
                        url: content_source_url,
                        picurl: thumb_url
                    });
                });
                rest = {...rest, articles}
            }

            // 发送客服消息
            const access_token = await UserService.getAccessToken(userID);
            const result = await WxCustomService.sendMessage({
                access_token,
                message: {
                    msgtype: msgType,
                    touser: toUser, [msgType]: {...rest}
                }
            });
            // 存储信息
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            let replyFromID = await MessageService.save({
                fromUser: appID,
                toUser,
                msgType,
                [msgType]: {...rest}
            });

            if (msgID) { // 插入到msgID回复列表|针对性发消息
                logger.debug("save", replyFromID);
                await MessageService.updateReplyList({replyFrom: replyFromID, replyTo: msgID}); // 更新
            }

            logger.debug(result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

router.post('/toggleStar', (req, res, next) => {
    (async () => {
        try {
            const {msgID, isStar} = req.body;
            if (!msgID) {
                let error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "MsgID不能为空";
                return next(error);
            }
            let result = await Message.toggleStar({msgID, isStar});
            logger.debug(result);
            res.status(200).json({
                errcode: 0,
                message: `msgID:${msgID}当前状态：${result.isStar ? "已" : "未"}收藏`
            });
        } catch (error) {
            next(error);
        }
    })();
});

router.get('/count', (req, res, next) => {
    (async () => {
        try {
            const dateReg = /^((?:19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/; // YYYY-MM-DD
            const {beginDate, endDate, msgType} = req.query;
            if (beginDate && !dateReg.test(beginDate)) {
                let error = new Error();
                error["errcode"] = 10002;
                error["errmsg"] = "开始时间参数格式不正确，YYYY-MM-DD";
                return next(error);
            }
            if (endDate && !dateReg.test(endDate)) {
                let error = new Error();
                error["errcode"] = 10002;
                error["errmsg"] = "结束时间参数格式不正确，YYYY-MM-DD";
                return next(error);
            }
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            let result = await Message.getCount({appID, msgType, beginDate, endDate});
            logger.debug(result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

export default router;
